<?php

namespace app\enterprise\controller;

use app\enterprise\model\staff\Staff as staffModel;
use app\enterprise\model\Parameter as parameterModel;
use app\enterprise\model\department\Department as departmentModel;
use app\enterprise\service\DataType;
use think\exception\ValidateException;
use app\enterprise\service\ImportService;
use app\enterprise\model\staff\StaffCert;
use think\facade\Request;
use app\enterprise\model\User as UserModel;

class Staff extends Enterprise
{


    public function allStaffs()
    {

        $include_ids = input('include_ids', []);
        $exclude_ids = input('exclude_ids', []);

        $staffs = staffModel::where('status', 1)
            ->where('company_id', $this->adminId)
            ->when(!empty($include_ids), function ($query) use ($include_ids) {
                $query->where('id', 'in' , $include_ids);
            })
            ->when(!empty($exclude_ids), function ($query) use ($exclude_ids) {
                $query->where('id', 'not in' , $exclude_ids);
            })
            ->select()->toArray();

        return app('json')->success([
            'list' => $staffs
        ]);
    }


    public function getStaffList()
    {
        $param = $this->request->param();

        $where = [];
        // $userIds = userIds($this->adminId);

        // 获取部门下的所有用户id
        $userIds = $this->getDepartmentUserIds();
        $where[] = ['creator_id', 'in', $userIds];
        $where[] = ['status', '=', 1];

        // 只显示在职的
        if ( !empty($param['is_job_status']) ) {
            $where[] = ['job_status', '=', 1];
        }

        if (!empty($param['username'])) {
            $where[] = ['username', 'like', '%' . $param['username'] . '%'];
        }
        if (!empty($param['idcard'])) {
            $where[] = ['idcard', 'like', '%' . $param['idcard'] . '%'];
        }
        if (!empty($param['staff_type'])) {
            $where[] = ['staff_type', '=', $param['staff_type']];
        }

        if (!empty($param['department_id'])) {
            // 获取该组织下所有组织
            $departments = departmentModel::getList([['status', '=', 1]]);
            $list = getCategoryWithChildren($departments, $param['department_id']);
            $department_ids = array_column($list, 'id');
            $where[] = ['department_id', 'in', $department_ids];
        }

//        if ( empty($param['job_select']) ) {
//            if (!empty($param['job_id'])) {
//                $where[] = ['job_id', '=', $param['job_id']];
//            }
//        } else {
//            if (!empty($param['job_ids'])) {
//                $where[] = ['job_id', 'in', $param['job_ids']];
//            }
//        }
        if (!empty($param['job_ids'])) {

            $departments = \app\model\basic\Parameter::getListByType(4);
            $list = [] ;
            foreach ($param['job_ids'] as $k=>$val){
                $list2 = getCategoryWithChildren($departments, $val);
                if($list2){
                    $list = array_merge($list , $list2) ;
                }
            }
            $jobIds = array_column($list, 'id');


            $where[] = ['job_id', 'in', $jobIds];
        }
        if (!empty($param['type_ids'])) {

            $departments = departmentModel::getList([['status', '=', 1]]);


            $list = [] ;
            foreach ($param['type_ids'] as $k=>$val){
                $list2 = getCategoryWithChildren($departments, $val);
                if($list2){
                    $list = array_merge($list , $list2) ;
                }
            }
            $jobIds = array_column($list, 'id');


            $where[] = ['department_id', 'in', $jobIds];
        }





        $include_ids = input('include_ids', []);
        $exclude_ids = input('exclude_ids', []);

        if (!empty($include_ids)) {
            $where[] = ['id', 'in' , $include_ids];
        }
        if (!empty($exclude_ids)) {
            $where[] = ['id', 'not in' , $exclude_ids];
        }

//        if (!empty($param['type_ids'])) {
//            $where[] = ['department_id', 'in', $param['type_ids']];
//        }

//        $list = staffModel::getList($where);
        $list = staffModel::getPage($where, $param['page'], $param['size']);
        $departments = departmentModel::getAlllist(['status' => 1]);

        $departs = array_column($departments, 'pidsstr', 'id');

        // 查询所有字典
        $dicts = parameterModel::listAll([]);
        // 将列表转为字典, key为id, value为name
        $dicts = array_column($dicts, 'para_name', 'id');

        // $departments = departmentModel::getList(['status' => 1]);

        $departments_list = array_column($departments, null, 'id');

        $departments = array_column($departments, 'department_name', 'id');

        $list->each(function ($item, $key) use ($dicts, $departs, $departments, $departments_list) {

            if (!empty($item->department_id) && isset($departments[$item->department_id])) {
                $item->department_name = $departments[$item->department_id]; // 组织架构名称

                $department_name = $departments_list[$item->department_id]['department_name'];
                if ( !empty($departments_list[$departments_list[$item->department_id]['pid']]) ) {
                    $department_name = $departments_list[$departments_list[$item->department_id]['pid']]['department_name'] . ' / ' . $department_name;
                }
                $item->department_path = $department_name;
            } else {
                $item->department_name = '未知';
                $item->department_name1 = '未知';
            }

            if (!empty($item->edu_id) && isset($dicts[$item->edu_id])) {
                $item->edu_name = $dicts[$item->edu_id];
            } else {
                $item->edu_name = '未知';
            }
            if (!empty($item->level_id) && isset($dicts[$item->level_id])) {
                $item->level_name = $dicts[$item->level_id];
            } else {
                $item->level_name = '未知';
            }
            if (!empty($item->job_id) && isset($dicts[$item->job_id])) {
                $item->job_name = $dicts[$item->job_id];
            } else {
                $item->job_name = '未知';
            }
            if (!empty($item->department_id) && isset($departs[$item->department_id])) {
                $item->pidstr = $departs[$item->department_id].','.$item->department_id;
            } else {
                $item->pidstr = ''.$item->department_id;
            }

            if ( !empty($item->idcard) ) {
                $item->idcard = idCardMask($item->idcard);
            }

        });

        // 市政集团的总账号，添加编辑的时候显示, 抓拍状态 和 倍速状态
        $role = false;
        if ( !empty($this->adminInfo['role']) && $this->adminInfo['role'] == 1 ) {
            $role = true;
        }


        return app('json')->success([
            'list' => $list->items(),
            'total' => $list->total(),
            'total_page'=>$list->lastPage(),
            'is_role'   => $role,
        ]);
    }


    public function saveStaff()
    {
        $param = $this->request->param();
        $param['company_id'] = $this->adminInfo['company_id'];;
        try {
            validate([
                'company_id|所属企业' => 'require',
                'department_ids|所属部门' => 'require',
                'username|名称' => 'require|max:255',
                'idcard|身份证号' => [
                    'require',
                    'regex:/^(\d{15}$|^\d{17}[\dXx])$/'
                ],
                'mobile|手机号' => [
                    'require',
                    'regex:/^1[3456789]\d{9}$/'
                ],
                // 'edu_id|学历' => 'require|number',
//                'level_id|人员级别' => 'require|number',
                'job_id|岗位' => 'require',
                // 'status|状态' => 'require|number',
                'appointment_img_url|任命图片'=>'max:255',
                'professional_certificate_img_url|专业证件照片'=>'max:255',
                'img_url|人员照片'=>'require',
//                'start_work_time|开始工作时间'=>'dateFormat:Y-m-d',
//                'entry_time|进场时间'=>'dateFormat:Y-m-d',
            ])->check($param);

            if ( is_array($param['job_id']) ) {
                $param['job_id'] = $param['job_id'][1] ;
            }
            if ( is_array($param['department_ids']) ) {
                $param['department_id'] = end($param['department_ids']);
            } else {
                $param['department_id'] = $param['department_ids'];
            }

            if (!empty($param['start_work_time'])) {
                $param['start_work_time'] = strtotime($param['start_work_time']);
            }
            else{
                $param['start_work_time'] = 0 ;
            }

            if (!empty($param['entry_time'])) {
                $param['entry_time'] = strtotime($param['entry_time']);
            }
            else{
                $param['entry_time'] = 0 ;
            }

            $certs = input('certs', []);
            if($certs){
                foreach ($certs as $key => $cert) {
                    try {
                        validate([
                            'type_id|资质类型' => 'require',
                            'cert_code|职业证书编号' => 'require',
                            'expire_type|是否永久有效' => 'require|in:1,2',
                            'start_time|证书有效期开始时间' => 'requireIf:expire_type,2',
                            'end_time|证书有效期结束时间' => 'requireIf:expire_type,2',
                            'cert_imgs|证书照片' => 'require',
                        ])->check($cert);
                        if ($cert['expire_type'] == 1) {
                            $cert['expire_type'] = 1;
                            $certs[$key]['start_time'] = 0;
                            $certs[$key]['end_time'] = 0;
                        } else {
                            $certs[$key]['start_time'] = strtotime($cert['start_time']);
                            $certs[$key]['end_time'] = strtotime($cert['end_time']);
                        }
                    } catch (ValidateException $e) {
                        return app('json')->fail($e->getError());
                    }
                }

            }

            $staffModel = new staffModel();
            if (empty($param['id'])) {

                // 判断手机号是否存在
                if ($staffModel->where('mobile', '=', $param['mobile'])->where('company_id', '=', $this->adminId)->where('status', '=', 1)->value('id')) {
                    return app('json')->fail('手机号已存在');
                }

                // 判断手机号是否存在
                if ($staffModel->where('idcard', '=', $param['idcard'])->where('company_id', '=', $this->adminId)->where('status', '=', 1)->value('id')) {
                    return app('json')->fail('身份证号已存在');
                }
                $password = substr($param['idcard'], -6);
                $param['password'] = md5($password);
//                $staffModel->add($param);
                $param['creator_id'] = $this->adminId;
                $res = staffModel::create($param);
                $param['id'] = $res->id;
            } else {
                $staff = staffModel::getOne($param['id']);
                if (empty($staff)) {
                    return app('json')->fail('要操作的数据不存在');
                }
//                if ($staff['company_id'] != $this->adminId) {
//                    return app('json')->fail('您没有权限操作该数据');
//                }

                if ($staff['mobile'] != $param['mobile']) {
                    if (staffModel::where('mobile', $param['mobile'])->where('company_id', $this->adminId)->where('status', 1)->value('id')) {
                        return app('json')->fail('手机号已存在');
                    }
                }

                if ($staff['idcard'] != $param['idcard']) {
                    if (staffModel::where('idcard', $param['idcard'])->where('company_id', $this->adminId)->where('status', 1)->value('id')) {
                        return app('json')->fail('身份证号已存在');
                    }
                }
                unset($param['create_time']) ;
                unset($param['update_time']) ;
                $staffModel->edit($param);
                StaffCert::arrayDelete(['staff_id' => $param['id']]);
            }

            if ($certs && is_array($certs) && count($certs) > 0) {
                foreach ($certs as $key => $cert) {
                    $certs[$key]['staff_id'] = $param['id'];
                }
                $staffCertModel = new StaffCert();
                $staffCertModel->saveAll($certs);
            }


            return app('json')->success('操作成功');
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
    }

    public function resetPassword()
    {
        $id = $this->request->param('id');
        $staff = staffModel::getOne($id);
        if (empty($staff)) {
            return app('json')->fail('要操作的数据不存在');
        }
        if ($staff->company_id != $this->adminId) {
            return app('json')->fail('您没有权限操作该数据');
        }
        $password = substr($staff['idcard'], -6);
        (new staffModel)->edit(['id' => $id, 'password' => md5($password), 'company_id' => $this->adminId]);
        return app('json')->success('重置成功');

    }

    public function staffInfo()
    {
        $id = $this->request->param('id');
        $staffModel = new staffModel();

        $data = staffModel::where('status', 1)->where('id', $id)->find();
        if (!empty($data)) {
            $edu = parameterModel::getOne($data['edu_id']);
            if (!empty($edu)) {
                $data['edu_name'] = $edu['para_name'];
            }
            $level = parameterModel::getOne($data['level_id']);
            if (!empty($level)) {
                $data['level_name'] = $level['para_name'];
            }
            $job = parameterModel::getOne($data['job_id']);
            if (!empty($job)) {
                $data['job_name'] = $job['para_name'];
            }

            if ($data['department_id'] > 0) {
                $data['department_name'] = departmentModel::getOne($data['department_id'])['department_name'];
            }

            $data['department_ids'] = $data['department_id'];
            if ($data['start_work_time']) {
                $data['start_work_time'] = date('Y-m-d', $data['start_work_time']);
            } else {
                $data['start_work_time'] = '';
            }

            if ($data['entry_time']) {
                $data['entry_time'] = date('Y-m-d', $data['entry_time']);
            } else {
                $data['entry_time'] = '';
            }


            $certs = StaffCert::where('staff_id', $id)->where('status', 1)->select()->toArray();

            if (!empty($certs)) {
                $cert_types = array_column(DataType::getStaffCertType(), 'name', 'id');
                foreach ($certs as $key => $cert) {
                    $certs[$key]['type_name'] = $cert_types[$cert['type_id']] ?? '';
                    // 格式化开始时间和结束时间, 格式 YYYY-MM-dd
                    if ($cert['expire_type'] == 1) {
                        $certs[$key]['start_time'] = '';
                        $certs[$key]['end_time'] = '';
                    } else {
                        $certs[$key]['start_time'] = date('Y-m-d', $cert['start_time']);
                        $certs[$key]['end_time'] = date('Y-m-d', $cert['end_time']);
                    }
                }
            }
            $data['certs'] = $certs;
        }

        return app('json')->success([
            'info' => $data
        ]);
    }


    public function deleteStaff()
    {
        $id = $this->request->param('id');
        staffModel::arrayDelete(['id' => $id, 'company_id' => $this->adminId]);
        return app('json')->success('删除成功');
    }

    /**
     * 导入人员信息
     */
    public function importStaff()
    {
        $file = Request::file('file');
        if (!$file) {
            return app('json')->fail('未上传文件');
        }

        try {
            $filePath = $file->getRealPath();

            $importService = new ImportService();
            $result = $importService->importStaff($filePath, $this->adminId, $this->adminId);

            return app('json')->success($result);
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());
        }
    }

    /**
     * 下载 Excel 导入模板
     */
    public function downloadImportTemplate()
    {
        $templatePath = app()->getRootPath() . 'public/template/staff_import_template.xlsx';

        if (!file_exists($templatePath)) {
            return app('json')->fail('模板文件不存在');
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="staff_import_template.xlsx"');
        header('Cache-Control: max-age=0');

        readfile($templatePath);
        exit;
    }

    public function certTypes()
    {
        $certTypes = DataType::getStaffCertType();
        return  app('json')->success([
            'certTypes' => $certTypes
        ]);
    }

    public function getDepartmentUserIds()
    {
        // 当前登录的pid
        $user_pid = $this->adminInfo['pid'];
        $departments = departmentModel::getList([['status', '=', 1]]);
        $list = getCategoryWithChildren($departments, $user_pid);
        $departments_ids = array_column($list, 'id');
        $user_ids = UserModel::where('pid', 'in', $departments_ids)->column('id');
        return $user_ids;
    }

}